import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import { message } from 'antd';
import { getToken } from '@/utils/auth';
// import { getInitialState } from '@umijs/max';
import './global.less';
const loginPath = '/user/login';

// 定义 API 接口类型
declare namespace API {
  type UserInfo = {
    name?: string;
    avatar?: string;
    userid?: string;
    permissions?: string[];
  };
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = getToken();
    if (!token) {
      throw new Error('No token found');
    }
    // 从本地存储获取用户信息
    const cachedUserInfo = localStorage.getItem('user_info');
    const cachedMenus = localStorage.getItem('menus');

    if (cachedUserInfo) {
      const userInfo = JSON.parse(cachedUserInfo);
      // 确保用户信息中包含菜单数据
      if (!userInfo.menus && cachedMenus) {
        userInfo.menus = JSON.parse(cachedMenus);
      }
      return userInfo;
    }

    // 如果本地没有，从服务器获取
    const msg = await getUserInfo();
    if (msg.code === 200 && msg.data) {
      localStorage.setItem('user_info', JSON.stringify(msg.data));
      return msg.data;
    }
    throw new Error(msg.msg || 'Failed to get user info');
  } catch (error) {
    console.error('Error fetching user info:', error);
    history.push(loginPath);
  }
  return undefined;
};

// 运行时配置
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  // fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  menus?: any[];
}> {
  // 获取当前路径
  const currentPath = window.location.pathname;

  // 权限检查
  const token = getToken();
  if (!token && currentPath !== loginPath) {
    history.push(loginPath);
    return {
      fetchUserInfo,
      settings: defaultSettings,
    };
  }

  // 如果是登录页面，不获取用户信息
  if (currentPath === loginPath) {
    return {
      fetchUserInfo,
      settings: defaultSettings,
    };
  }

  // 获取用户信息
  const currentUser = await fetchUserInfo();
  console.log('Current user with menus:', currentUser);
  return {
    fetchUserInfo,
    currentUser,
    settings: defaultSettings,
    menus: currentUser?.menus || [],
  };
}

// 运行时布局配置
export const layout: RunTimeLayoutConfig = ({ initialState }) => ({
  actionsRender: () => [<Question key="doc" />, <SelectLang key="SelectLang" />],
  avatarProps: {
    src: initialState?.currentUser?.avatar,
    title: <AvatarName />,
    render: (_, avatarChildren) => {
      return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
    },
  },
  // footerRender: () => <Footer />,
  onPageChange: () => {
    // 如果没有登录，重定向到登录页面
    const token = getToken();
    const { location } = history;
    if (!token && location.pathname !== loginPath) {
      history.push(loginPath);
    }
  },
  menuHeaderRender: undefined,
  ...initialState?.settings,
});

export const request = {
  timeout: 10000,
  requestInterceptors: [
    (url: string, options: any) => {
      console.log('url1111111111111111:', url);
      console.log('options:', options);
      const token = getToken();
      return {
        url,
        options: {
          ...options,
          headers: {
            ...options.headers,
            'dhcc-auth': token || '',
          },
        },
      };
    },
  ],
};
